package nu.aing.P20140811;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author memekmaut@gmail.com
 */
public class HappyLetterDiv2 {
    
    public static void main(String[] args) {
        HappyLetterDiv2 obj = new HappyLetterDiv2();
        System.out.println(obj.getHappyLetter("aacaaa") );
        System.out.println(obj.getHappyLetter("dcdjx") );
        System.out.println(obj.getHappyLetter("bcbbbbba") );
        System.out.println(obj.getHappyLetter("aabc") );
    }
    
    public char getHappyLetter(String letters) {
        char[] cs = letters.toCharArray();
        Arrays.sort(cs);
        List<Character> fronts = new LinkedList<Character>();
        List<Character> ends = new LinkedList<Character>();
        
        for(int i = 0; i < cs.length; i++) {
            fronts.add(cs[i]);
            ends.add(cs[i]);
        }
        
        Character c1 = null, c2 = null;
        boolean frontfound = false, endfound = false;
        while(true) {
            frontfound = endfound = false;
            for(int i = 0; i < fronts.size() - 1; i++) {
                c1 = fronts.get(i);
                c2 = fronts.get(i+1);
                if(c1 != c2) {
                    frontfound = true;
                    fronts.remove(c1);
                    fronts.remove(c2);
                    break;
                }
            }
            for(int i = ends.size() - 1; i > 0; i--) {
                c1 = ends.get(i);
                c2 = ends.get(i-1);
                if(c1 != c2) {
                    endfound = true;
                    ends.remove(c1);
                    ends.remove(c2);
                    break;
                }
            }
            
            if((frontfound == false && endfound == false) ) {
                if(fronts.size() > 0 && ends.size() > 0 && fronts.get(0) == ends.get(0) ) {
                    return fronts.get(0);
                }
                return '.';
            }
        }
    }
}
